package com.zsgeek.wisdchain.qutu.tools;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.zsgeek.wisdchain.qutu.R;
import com.zsgeek.wisdchain.qutu.base.event.BaseEvent;
import com.zsgeek.wisdchain.qutu.base.event.BaseEventBusHelper;
import com.zsgeek.wisdchain.qutu.popup.dialog.DialogUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Headers;

/**
 * 下载升级安装
 */

public class DownloadApkManager<T> {
    private String apkName = "WDCWalletRelease.apk";
    private Context context;

    public DownloadApkManager(Context context) {
        this.context = context;
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x004:
                    openProgressDialog(context.getString(R.string.downloading), context.getResources().getString(R.string.download_progress));
                    break;
                case 0x005:
                    dismissDialog();

                    handler.removeCallbacksAndMessages(null);
                    EventBus.getDefault().post(new BaseEvent<>(BaseEventBusHelper.EVENT_INSTALLAPK));
                    break;
                case PRO:
                    if (progressDialog != null && progressDialog.isShowing())
                        progressDialog.setProgress(progress);
                    break;
                case 0x006:
                    ToastHelper.showToast((String) msg.obj);
                    dismissDialog();
                    break;
            }

            super.handleMessage(msg);
        }
    };

    private final int PRO = 10;
    private int progress = 0;
    private ProgressDialog progressDialog;

    //    下载进度条弹框
    private void openProgressDialog(String title, String message) {
        if (progressDialog != null) {
            if (progressDialog.isShowing())
                progressDialog.dismiss();
            progressDialog = null;
        }
        progressDialog = new ProgressDialog(context);
        progressDialog.setIcon(R.mipmap.ic_launcher);
        progressDialog.setTitle(title);
//        progressDialog.setMessage(message);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//设置进度条对话框//样式（水平，旋转）
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressDrawable(context.getResources().getDrawable(R.drawable.download_apk_progressdialog));
        //设置对话进度条显示在屏幕顶部（方便截图）
        //        progressDialog.getWindow().setGravity(Gravity.CENTER);
        //进度最大值
        progressDialog.setMax(100);

        this.progressDialog.show();
        progress = (progress > 0) ? progress : 0;
        progressDialog.setProgress(progress);
        if (handler != null)
            handler.sendEmptyMessage(PRO);
    }

    private void dismissDialog() {
        if (handler != null) {
            handler.removeMessages(PRO);
        }
        if (progressDialog != null) {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            progressDialog = null;
        }
    }

    protected <T> void handleError(Response<T> response) {
        if (response == null) return;
        if (response.getException() != null) response.getException().printStackTrace();
        StringBuilder sb;
        Call call = response.getRawCall();
        if (call != null) {
            LogUtil.e("请求失败  请求方式：" + call.request().method() + "\n" + "url：" + call.request().url());

            Headers requestHeadersString = call.request().headers();
            Set<String> requestNames = requestHeadersString.names();
            sb = new StringBuilder();
            for (String name : requestNames) {
                sb.append(name).append(" ： ").append(requestHeadersString.get(name)).append("\n");
            }
            LogUtil.e(sb.toString());
        } else {
            LogUtil.e("--");
        }

        LogUtil.e("--");
        okhttp3.Response rawResponse = response.getRawResponse();
        if (rawResponse != null) {
            Headers responseHeadersString = rawResponse.headers();
            Set<String> names = responseHeadersString.names();
            sb = new StringBuilder();
            sb.append("stateCode ： ").append(rawResponse.code()).append("\n");
            for (String name : names) {
                sb.append(name).append(" ： ").append(responseHeadersString.get(name)).append("\n");
            }
            LogUtil.e(sb.toString());
        } else {
            LogUtil.e("--");
        }
    }

    private <T> void downloadApk(final String downApkPath) {
        File file = new File(UrlPathHelper.PATH_APK);
        if (!file.exists()) {
            file.mkdirs();
        }

        File ApkFile = new File(UrlPathHelper.PATH_APK + apkName);
        if (ApkFile.exists())
            ApkFile.delete();

        OkGo.<File>get(downApkPath)
                .tag(0x640121)
                .headers("Connection", "close")
                .execute(new FileCallback(UrlPathHelper.PATH_APK, apkName) {

                    @Override
                    public void onStart(Request<File, ? extends Request> request) {
                        if (handler != null)
                            handler.sendEmptyMessage(0x004);
                    }

                    @Override
                    public void onSuccess(Response<File> response) {
                        if (handler != null)
                            handler.sendEmptyMessage(0x005);
                    }

                    @Override
                    public void onError(Response<File> response) {
                        handleError(response);
                        handler.sendMessage(handler.obtainMessage(0x006, context.getResources().getString(R.string.download_error)));
                    }

                    @Override
                    public void downloadProgress(Progress progressDown) {
                        progress = (int) (progressDown.fraction * 100);
                        if (handler != null)
                            handler.sendEmptyMessage(PRO);
                    }
                });

    }

    public void TipsDialog(String message, String url) {
        DialogUtil.createDefaultDialog(context, context.getResources().getString(R.string.version_update), message,
                context.getResources().getString(R.string.upgrade_now), dialog -> {
                    dialog.dismiss();
                    downloadApk(url);
                });
    }

}
